<?php
namespace app\api\controller;
use think\Db;
use think\request;
use think\Controller;
use app\index\model\UserModel;
use app\index\model\MemberVerifModel;
use app\index\model\ComplainModel;
use app\common\controller\ApiBaseController;

class App extends ApiBaseController
{
	protected function _initialize() {
		parent::_initialize();
	}
	
	public function agent_details(){
		$data = db('info_agent')->where('id',input('agent_id'))->find();
		$data['longitude']=$data['longitude']?$data['longitude']:'113.013481';
		$data['latitude']=$data['latitude']?$data['latitude']:'25.773369';
		$ads=db('agent_advertisement')->where('agent_id',input('agent_id'))->select();
		$wh['agent_id']=input('agent_id');
		$wh['goods_state']=2;
		$wh['is_recommend']=2;
		$goods=db("agent_goods")->where($wh)->limit(5)->select();
		return json(["agent"=>$data,"ads"=>$ads,"goods"=>$goods]);
	}
	//收银员个人信息
	public function clerk(){
		$clerk=db('agent_clerk')
		->alias('a')
		->join('agent_store w','a.chain_id = w.id')
		->where('a.id',input("clerk_id"))
		->field('a.*,w.store_name')
		->find();
		return json(["clerk"=>$clerk]);
	}
	
	//APP首页数据
	public function app_index(){
		$where['clerk_id']=input("clerk_id");//员工id
		$emp=db("agent_clerk")->field("agent_id")->find(input("clerk_id"));
		$agent=db('info_agent')->find($emp["agent_id"]);
        $where['state']=2;
		$res=db("log_paylog")->where($where)->whereTime("add_time","yesterday")->sum('balance');
		$price=$res?$res:0;
		$res1=0;
		if($agent&&$agent['user_id']){
			$res1=db("info_user")->where("level",$agent['user_id'])->whereTime("add_time","yesterday")->count();
		}
		
		return json(["clerk"=>['shoukuan'=>$price,'member'=>$res1]]);
	}
	public function get_version(){
		$version="2";
		$url="https://fir.im/longxinyun";
		return json(["version"=>$version,"url"=>$url]);
	}
	
	//我的会员
	public function member_list(){
		$agent=db('info_agent')->find(input("agent_id"));
		$where['level']=$agent['user_id'];
		if(input("mobile")){
			$where['mobile']=["like","%".input("mobile")."%"];
		}
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		$pg=$page-1;
		$begin=$pg*10;
		$end=$begin+10;
		$list=db('info_user')->where($where)->limit($begin,$end)->select();
		return json(["list"=>$list]);
	}
	
	//收银帐本
	public function log_list(){
		$where['state']=2;
		$where['clerk_id']=input("clerk_id");    
		$log_list=db('log_paylog')->where($where)->whereTime("add_time","today")->field("balance,order_sn,add_time,score")->select();
		return json(["log_list"=>$log_list]);
	}
	//更新APP版本Version
	public function Version(){  
		return json(["date"=>['version'=>"4",'vurl'=>"http://lxy.ilong3.com/4.1.apk"]]);
	}
	
	//用户登录
	public function login(){
        $param=input();
    		
    	$where['mobile'] 	= $param['mobile'];
    	$where['password'] 	= md5_salt($param['pwd']);
    	$where['oem_id'] 	= config('cut_oem_id');
    		
    	$user_info = db('info_user')->where($where)->find();
    	if($user_info){
    		if($user_info['status'] == 1){
    			return json(["msg"=>'登录成功','data'=>$user_info]);
    		}else{
    			return json(["msg"=>'账号异常，已冻结!']);
    		}
    	}else{
    		return json(["msg"=>'用户名密码错误']);
    	}
        
	}
	
	 /**
     * 获取验证码
     * 注意防盗刷
     * 
     */
    function verify_code(){
    	return get_code(input('mobile'));
    }
	
	//用户注册
	function regist_user(){
		$mobile 	 = input('mobile');
		$pwd 		 = input('pwd');
		$yzm 		 = input('yzm');
		$openid 	 = input('openid');
		$alipay_id 	 = input('alipay_id');
		$from_mobile = input('from_mobile');
		
		//检查验证码
		$result = check_sendcode($mobile, $yzm, '发送成功');
		if($result != 1) {
			return json(["msg"=>'验证码错误或过期']);
		}
		
		$user_info = db('info_user')->where('mobile',$mobile)->find();
    	//检查手机号码
	    if($user_info){
	    	return json(["msg"=>'该手机号码已经注册']);
	   	}
	   	$open_user = 0;
    	//检查openid
	   	if($openid && strlen($openid) >2){
	   		//查找用户信息
	   		$open_user = db('info_user')
    					->where('openid',$openid)
    					->find();
    		$cut_user['openid'] 	= $openid;
	   	}else if($alipay_id && strlen($alipay_id) >2){
	   		//查找用户信息
	   		$open_user = db('info_user')
    					->where('alipay_id',$alipay_id)
    					->find();
    		$cut_user['alipay_id'] 	= $alipay_id;
	   	}
	   	if($open_user){
	   			$pwd = md5_salt($pwd);
	   			//更新用户信息
	   			$resut = Db::table('info_user')
	   						->where('id', $open_user['id'])
	   						->update(['password' => $pwd,'mobile'=>$mobile]);
	   			if($resut){
	   				return json(["msg"=>'登录成功','user_id'=>$open_user['id']]);
	   			}else{
	   				return json(["msg"=>'注册失败402']);
	   			}
	   			
	   	}else{
	   		if($from_mobile && strlen($from_mobile)>2){
	   			//有推荐人
	   			$from_info = db('info_user')->where('mobile',$from_mobile)->find();
	   		}else{
	   			//无推荐人
	   			$from_info = db('info_user')->where('mobile',1)->find();
	   		}
	   		$cut_user['mobile'] 	= $mobile;
	   		$cut_user['password'] 	= md5_salt($pwd);
	   		$cut_user['level'] 		= $from_info['id'];
	   		$cut_user['oem_id'] 	= $from_info['oem_id'];
	   		$cut_user['agency_id1'] = $from_info['agency_id1'];
	   		$cut_user['agency_id2'] = $from_info['agency_id2'];
	   		$cut_user['form_agent'] = $from_info['form_agent'];
	   		$cut_user['add_time'] 	= now_time();
	   		
	   		$user_model = new UserModel();
			
			$rest=$user_model->allowField(true)->save($cut_user);
			
			$userId = $user_model->getLastInsID();

			if($rest){
				return json(["msg"=>'登录成功','user_id'=>$userId]);
			}
	   	}
    }
    
    
    //首页商家列表
    function index_agetn_list(){
    	$longitude = input('longitude');
		$latitude = input('latitude');
		$order = ' order by juli asc ';
		$where =" where status = 1 and oem_id = ".config('cut_oem_id');
		$field='a.action,a.is_score,ad_score,a.start_time,a.end_time,a.id,a.agent_name,a.add_time,a.logo,a.address,a.longitude,a.latitude,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli';
		$sql = 'select '.$field.' from info_agent as a '.$where.$order;
		$resultList=Db::query($sql);
		return json(["list"=>$resultList]);
    }
    
    
    //商家店铺页面
    function agent_index(){
    	$data = db('info_agent')->where('id',input('agent_id'))->find();
		$data['longitude']=$data['longitude']?$data['longitude']:'113.013481';
		$data['latitude']=$data['latitude']?$data['latitude']:'25.773369';
		$ads=db('agent_advertisement')->where('agent_id',input('agent_id'))->select();
		$wh['agent_id']=input('agent_id');
		$wh['goods_state']=2;
		$goods=db("agent_goods")->where($wh)->limit(4)->select();
		$result_data['agent_info']  = $data;
		$result_data['goods_list']  = $goods;
		$result_data['ads'] 		= $ads;
		
        return  json(["data"=>$result_data]);
    }
    
    
    //获取商品详情
    function goods_by_id(){
    	//商品信息
    	$goods_info = db('agent_goods')
						->where('id',input('goods_id'))
						->find();
		//商品评价
		$goods_evaluate = db('agent_evaluate')
						->where('goods_id',$goods_info['id'])
						->order('add_time desc')
						->limit(5)
						->select();
		$goods_info['content'] = html_entity_decode($goods_info['content']);
		$goods_info['goods_evaluate'] = $goods_evaluate;
		
		if($goods_info){
			return  json(["data"=>$goods_info]);
		}else{
			return  json(["msg"=>'商品不存在']);
		}
    }
    
    //用户鼓励金
    function user_score(){
    	$user_id = input('user_id');
    	$info_user = db('info_user')->where('id',$user_id)->find();
		$logs=db('log_user_score')->where("u_id",$user_id)->order('add_time desc')->limit(10)->select();
		$this->assign("logs",$logs);
    	$this->assign('info_user',$info_user);
    	$info_user['user_logs'] = 	$logs;
		    	
		return  json(["data"=>$info_user]);
    }
    
    //用户鼓励金记录
    function score_log_list (){
    	$user_id = input('user_id');
		$cut_page = input('cut_page');
		$cut_num = $cut_page*10;
		$logs=db('log_user_score')->where("u_id",$user_id)->order('add_time desc')->limit($cut_num,20)->select();  	
		
		return  json(["data"=>$info_user]);
    }
    
    //获取用户信息
    function user_by_id(){
    	$user_id = input('user_id');
    	$info_user = db('info_user')->where('id',$user_id)->find();
    	
    	return  json(["data"=>$info_user]);
    }
    
    //鼓励金充值
	function socre_cz(){
		$order_sn = order_create_no();
		$user_id  = input('user_id');
		$info_user = db('info_user')->where('id',$user_id)->find();
		$cz_money = input('money');
		$pay_type = input('pay_type');
		
		//充值日志
		recharge_log($info_user['id'], $cz_money, 8, $order_sn, $pay_type, '用户充值鼓励金', $info_user['oem_id']);
		
		if($cz_money < 100){
			$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/member/glj';
		}else{
			$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/member/friends';
		}
		
		if($pay_type==3){//支付宝
	        $url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_money,1,$order_sn,'',$redirect_url);
		}elseif ( $pay_type==2 ) {//微信扫码
			$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$cz_money,2,$order_sn,'',$redirect_url);
		}
		return json(["code"=>200,"url"=>$url]);
	}    
	
	/**
	 * give_user_id 转账用户id
	 * get_user_mobile 收款用户电话
	 * money 金额变化值
	 * operate_pwd 操作密码
	 */
	//鼓励金转账
	function accounts(){
		$give_user_id = input('give_user_id');
    	$info_user = db('info_user')->where('id',$give_user_id)->find();
		$much=input("money");//转账金额
		if($much>$info_user['score']){
			return json(["code"=>400,'msg'=>'鼓励金余额不足']);
		}
		$no=input("get_user_mobile");//转账账号
		$user=db("info_user")->where('mobile',$no)->find();
		if(!$user){
			return json(["code"=>400,'msg'=>'转账账号不存在']);
		}
		$operate_pwd=input("operate_pwd");//转账金额
		//检查操作密码
		if($info_user['operate_pwd'] != md5_salt($operate_pwd)){
			return json(["code"=>400,'msg'=>'操作密码错误']);
		}
		Db::startTrans();
		$res=user_score_change($info_user['id'],8,-$much,'鼓励金转账扣除鼓励金',$info_user['id'],$user['id']);
		if($res){
			$sql="update info_user set score=score-$much where id=".$info_user['id'];
			$res1=DB::execute($sql);
			if($res1){
				$res2=user_score_change($user['id'],8,$much,'鼓励金转账收款',$info_user['id'],$user['id']);
				if($res2){
					$sql="update info_user set score=score+$much where id=".$user['id'];
					$res3=DB::execute($sql);
					if($res3){
						$balance=bcmul($much, 0.05, 4);//扣除5%手续费到到龙信平台
						$res4=oem_score_change(8,$balance,'用户鼓励金转账',1);
						if($res4){
							$sql="update info_oem set score=score+$balance where id=1";
							$res5=DB::execute($sql);
							if($res5){
								Db::commit();
								return json(["code"=>200,'msg'=>'转账成功']);
							}
						}
					}
				}
			}		
		}
		Db::rollback();
		return json(["code"=>400,'msg'=>'转账失败']);
	}
	
	/**
	 * user_id 用户id
	 * money 变化金额
	 * 鼓励金转余额
	 */
	function glj_tixian(){
		$user_id = input('user_id');
    	$info_user = db('info_user')->where('id',$user_id)->find();
		$much=input("money");//鼓励金转余额10：1
		$oem_much=bcmul($much, 0.005, 4);//扣除5%手续费到到龙信平台
		$balance=bcmul ($much,0.095, 4);//
		if($much>$info_user['score']){
			return json(["code"=>400,'msg'=>'鼓励金余额不足']);
		}
		Db::startTrans();
		$res=user_score_change($info_user['id'],9,-$much,'鼓励金兑现扣除鼓励金');
		if($res){
			$res1=admin_charge($oem_much,1,$info_user['id'],0,'用户兑现');
			if($res1){
				$res2=user_money_change($info_user['id'],4,$balance,1,'鼓励金兑现');
				$sql="update info_user set score=score-$much,balance=balance+$balance where id=".$info_user['id'];
				if($res2){
					$res3=DB::execute($sql);
					if($sql){
						Db::commit();
						$cut_user_info = db('info_user')->where('id',$user_id)->find();
						return json(["code"=>400,'msg'=>'兑现成功','user_info'=>$cut_user_info]);
					}
				}
			}
			
		}
		 Db::rollback();
		 return json(["code"=>400,'msg'=>'兑现失败']);
	}
	
	//用户余额记录
	function balance_log(){
		$user_id = input('user_id');
		$cut_page = input('cut_page');
		$cut_num = ($cut_page - 1)*10;
		$loglist = db('log_user_charge')->where("u_id",$user_id)->order('add_time desc')->limit($cut_num,10)->select();  	
		
		return  json(["data"=>$loglist]);
	}
	
	//余额提现
	function member_tixian(){
		$user_id = input('user_id');
		$balance = input('balance');
		//获取用户信息
		$info_user = db('info_user')->where('id',$user_id)->find();
		$result = true;
		
		// 启动事务
		Db::startTrans();			
		try{
			//用户累计收入
			$user_total_money = db('log_user_charge')
										->where('u_id',$info_user['id'])
										->where('balance','>',0)
										->sum('balance');
			//检查累计收入 
			if(bccomp($user_total_money, $info_user['total_income'], 4) != 0){
				return json(['code'=>405,'msg'=>'提交申请失败']);
			}
			//计算用户余额 = 累计收入 - 累计提现金额
			$user_cut_money = bcsub($user_total_money, $info_user['total_withdrawals_money'], 4);
			//检查用户余额 
			if(bccomp($user_cut_money, $info_user['balance'], 4) != 0){
				return json(['code'=>403,'msg'=>'提交申请失败']);
			}
			//检查提现金额，核对余额是否合法
			if(bccomp($info_user['balance'], $balance, 4)>=0){
				//计算当前余额
				$cut_balance = bcsub($info_user['balance'], $balance, 2);
				//计算当前累计提现
				$cut_total_withdrawals = bcadd($info_user['total_withdrawals_money'], $balance, 2);
				//更新用户信息
				$rest1 = db('info_user')
							->where('id', $info_user['id'])
							->update([
								'total_withdrawals_money' => $cut_total_withdrawals,
								'balance'=>$cut_balance
								]);
				if(!$rest1) $result = false;
			
				//用户提现，余额变化日志
				$rest2 = user_money_change($info_user['id'],1,-$balance,'余额提现');
				if(!$rest2) $result = false;
				
				//提现日志
				$rest3 =withdrawals_log($info_user['id'],2,$balance,$balance,$rest2);
				if(!$rest3) $result = false;
				
				if($result){
					// 提交事务
    				Db::commit();
					return json(['code'=>200,'msg'=>'提交成功']);
				}else{
					//回滚
		    		Db::rollback();
					return json(['code'=>402,'msg'=>'提交失败']);
				}
			}else{
				return json(['code'=>402,'msg'=>'提交失败']);
			}
		}catch ( Exception $e ) {
		    //$e->getMessage();
		    //回滚
		    Db::rollback();
		    exit;
		}
	}
	
	//分享资格
	function share_aptitude(){
		return json(['code'=>402,'data'=>config('limit_money')]);
	}
	
	//图片上传
    public function upload(){
    	include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
		$files = $_POST["value"];  
	    $tmp = base64_decode($files);
	    $fn = time()."_".rand(100000, 999999) . ".jpg";
		$fp = '././public/uploads/image/'. $fn;
		$fp1 = '././public/uploads/image/'. $fn;
	    $res=file_put_contents( $fp, $tmp);
		$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
		try{
			$res=$ossClient->uploadFile("long3",$fn,$fp1);
			$src='https://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
			unlink($fp1);
			return json(["code"=>200,'url'=>$src]);
		} catch(OssException $e) {
			return json(["code"=>404,'msg'=>'上传错误']);
		} 
	}
	
	//用户认证
	function user_approve(){
		$param=input('post.');
		$member_verif = new MemberVerifModel();
		$param['user_id']	= $info_user['id'];
		$verif_info = db('sys_member_verif')->where('user_id',$info_user['id'])->find();
		if($verif_info){
			$result = $member_verif -> where('id',$verif_info['id']) -> update($param);
		}else{
			$param['add_time']	= now_time();
			$param['oem_id']	= $info_user['oem_id'];
			$result = $member_verif -> allowField(true)-> save($param);
		}
		//更新用户认证状态
		$result = db('info_user')->where('id',$info_user['id']) -> update(['is_verify'=>2]);
		if($result){
			$this->success('成功');
		}else{
			$this->error('失败');
		}
	}
	
	//会员分享
	public function share_erweim(){
		$user_id = input('user_id');
    	$info_user = db('info_user')->where('id',$user_id)->find();
		//二维码链接
    	$code_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=".session('info_user')['id'];
		
		return json(["code"=>200,'data'=>$code_url]);
	}
	
	
	//获取用户订单
	function order_list(){
		$user_id 	= input('user_id');
		$status 	= input('status');
		$where['a.user_id']=$user_id;
		$where['a.type']=4;
		if($status && $status>0){
			$where['a.status']=$status;
		}
		$orders=db("agent_syorder")
					->alias("a")
					->join("info_agent i","i.id=a.agent_id")
					->join("agent_goods g",'a.goods_id=g.id')
					->where($where)
					->select();
		
		return json(["code"=>200,'data'=>$orders]);
	}
	
	//下单
	function add_order(){
		$user_id	=input('user_id');
		$goods_id	=input("goods_id");	//商品id
		$nums		=input('nums');			//商品数量
		$content 	=  input('content');	//用户留言
		
		$cut_url = "http://".$_SERVER['HTTP_HOST']."/index/index/pay_order?good_id=$goods_id&nums=$nums&user_id=$user_id&content=$content";
		$order_pay_url='http://www.vshop88.net/code/code.php?url='.urlencode($cut_url).'&margin=1&size=10';
		
		return json(["code"=>200,'data'=>$cut_url]);
	}
	
	//订单付款
	function pay_order(){
		$goods_id 	= input('good_id');
		$nums 		= input('nums');
		$user_id 	= input('user_id');
		$content 	= input('content');
		
		$goods=db("agent_goods")->field("agent_id,dk_price,zs_price,oem_id,sale_price")->find($goods_id);
		$agent=db('info_agent')->find($goods['agent_id']);
		
		$type=get_brower_type();//判断是微信还是支付宝打开
		if($type==1){
			$pay_type=3;
		}else{
			$pay_type=2;
		}
		$p_score=0;//抵扣鼓励金
		$zs_score=0;//赠送鼓励金
		$price=$goods['sale_price']*$nums;//订单价
		$pay_price=$price;//实际支付价格
		$this->do_pay($goods,$agent,$p_score,$zs_score,$pay_price,$user_id);
		$sn=order_create_no();
		Db::startTrans();
		$res=$this->add_syorder($goods_id,$sn,$agent["id"],$pay_type,$p_score,$zs_score,$price,$pay_price,$user_id,1,4,input('content'));
		if(!$res){
			Db::rollback();
			echo '下单失败';exit;
		}
		$log_res=add_log($nums,$goods_id,$user_id,$agent['id'],0,'',$sn,$pay_type,1,$price,
		$pay_price,1);
		if(!$log_res){
			Db::rollback();
			echo '下单失败';exit;
		}
		Db::commit();
		if($pay_price==0){//纯积分
			header("Content-type: text/html; charset=utf-8"); 
			echo '支付成功';exit;
		}
		if($type==1){//支付宝
	        if($agent['is_state']==1){
        		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
				Header("Location: $url");
				exit;
        	}else{
        		header("Content-type: text/html; charset=utf-8"); 
        		echo '支付失败';exit;
        	}
		}elseif ( $type==2 ) {//微信扫码
				if($agent['is_state']==1){
        			$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,2,$sn,'');
					Header("Location: $url");
					exit;
	        	}else{
					header("Content-type: text/html; charset=utf-8"); 
	        		echo '支付失败';exit;
	        	}
		}
	}
	
	//意见反馈
	function feedback(){
		
		$data['pid'] 		= input('type');
		$data['content'] 	= input('content');
		$data['add_time'] 	= now_time();
		$data['oem_id']  	= 1;
	
		$result = Db::table('sys_complain')->insert($data);
		
		if($result){
			return json(["code"=>200,'msg'=>'添加成功']);
		}else{
			return json(["code"=>403,'msg'=>'添加失败']);
		}
	}
	
	
	//获取用户openid
	function get_user_openid(){
		return wx_open_id(input('auth_code'));
	}
	
	//用户推广中心
    public function friends()
    {	
    	$info_user = db('info_user')->where('id',input('user_id'))->find();
		if($info_user['is_fx']!=1){
    		$this->redirect('index/member/open_fx');
    	}
		$myfriends=db("info_user")->where("level",$info_user['id'])->count();
		$data['myfriends'] = $myfriends;
    	
    	$where['u_id'] = $info_user['id'];
    	$where['operator'] = 1;
		$commission_income =db('log_user_commission')->where($where)->sum('balance');
    	
    	//二维码链接
    	$redirect_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=".$info_user['id'];
		
		$info_user['code_url'] = $redirect_url;
    	
    	//用户头像
    	$info_user['logo'] = strlen($info_user['logo'])>2?$info_user['logo']:"/public/static/logo/1/logomr.png";
    	
    	//累计佣金
    	$info_user['commission_income'] = substr($commission_income>0?$commission_income:"0.00",0,4);;
    	
		$wh['order_type']=10;
		$wh['u_id']=$info_user['id'];
		$today_glj=db("log_user_score")->where($wh)->whereTime("add_time",'today')->sum("balance");
		$total_glj=db("log_user_score")->where($wh)->sum("balance");
		$wo['order_type']=10;
		$wo['u_id']=$info_user['id'];
		$loglist=db('log_user_score')->where($wo)->paginate(10);
		$data['loglist'] = $loglist;
		$data['today_glj'] = $today_glj?$today_glj:0;
		$data['total_glj'] = $total_glj?$total_glj:0;
		$data['info_user'] = $info_user;
    	
       	return json(["code"=>403,'data'=>$data]);
    }
	
}
		
		

